package com.dai.zhenfujin.my.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.HistoryBean;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.utils.PhotoUtil;
import com.dai.zhenfujin.utils.UIUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_CAMERA_REQUEST;
import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_GALLERY_REQUEST;
import static com.dai.zhenfujin.my.activity.ReleaseActivity.CODE_RESULT_REQUEST;
import static com.dai.zhenfujin.visitingcard.activity.AlumActivity.RC_CHOOSE_PHOTO;
import static com.dai.zhenfujin.visitingcard.activity.AlumActivity.RC_PHOTO_PREVIEW;


public class CompanyActivity extends BaseActivity implements View.OnClickListener, BGASortableNinePhotoLayout.Delegate {
    private TextView tvName;
    private FrameLayout imageView;
    private ImageView company_imageview;
    private EditText etName,company_name_code;
    private Button company_button;
    private Dialog dialog;
    private OSS oss;
    private boolean isShowImg;
    private Uri cropImageUri;
    private static int OUTPUT_X = 480;
    private static int OUTPUT_Y = 480;
    private Uri imageUri,imageUri2;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private BGASortableNinePhotoLayout mPhotosSnpl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        tvName = (TextView) findViewById(R.id.title_textview);
        imageView = findViewById(R.id.fl_img);
        etName = (EditText) findViewById(R.id.company_name);
        company_imageview = findViewById(R.id.company_imageview);
        company_button = findViewById(R.id.company_button);
        company_name_code = findViewById(R.id.company_name_code);
        mPhotosSnpl =  findViewById(R.id.snpl_moment_add_photos);

        tvName.setText("企业认证");
    }

    private void initListener() {
        imageView.setOnClickListener(this);
        company_imageview.setOnClickListener(this);
        company_button.setOnClickListener(this);
        mPhotosSnpl.setDelegate(this);
    }

    private void initData() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("auth_type","2");
        params.put("req_bd",  params2);
        HttpClient.post(this, Constants.AUTH_HISTORY, params, new CallBack<HistoryBean>() {
            @Override
            public void onSuccess(HistoryBean historyBean) {
                etName.setText(historyBean.getAuth_name());
                company_name_code.setText(historyBean.getAuth_code());
                if (historyBean.getAuth_state().equals("1")){
                    company_button.setText("审核成功");
                }else if (historyBean.getAuth_state().equals("2")){
                    company_button.setText("未审核通过");
                }else {
                    company_button.setText("正在审核中");
                }

                if (historyBean.getUrl_list() != null && historyBean.getUrl_list() .size() > 0)
                 //   Glide.with(CompanyActivity.this).load(historyBean.getUrl_list().get(0)).into(company_imageview);
                    mPhotosSnpl.addMoreData((ArrayList<String>)historyBean.getUrl_list());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_img://返回
                finish();
                break;
            case R.id.company_imageview:
               // showDialog();
                break;
            case R.id.company_button://认证
                if (company_button.getText().toString().equals("正在审核中")){
                    return;
                }
                if (TextUtils.isEmpty(etName.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入公司名称");
                    return;
                }
                if (TextUtils.isEmpty(company_name_code.getText().toString().trim())) {
                    UIUtils.showToastSafe("请输入公司营业执照编码");
                    return;
                }


                if (mPhotosSnpl != null && mPhotosSnpl.getData().size() > 0) {
                    if (UIUtils.isFastClick())
                    initOss(); //配置OSS
                    ossToken(revitionImageSize(mPhotosSnpl.getData().get(0)));
                } else {
                    UIUtils.showToastSafe("请先添加图片");
                }

                break;
            case R.id.dialog_shoot://拍摄
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
               // dialog.dismiss();

                break;
            case R.id.dialog_photo_album://相册
                //PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
             //   dialog.dismiss();

                break;
            case R.id.dialog_cancel://取消
              //  dialog.dismiss();
                break;
        }
    }

    private void ossToken(String path) {
        // 构造上传请求
        final String imgName = UIUtils.getCurTimeMills() + "";
        PutObjectRequest put = new PutObjectRequest("zenfujin-bucket", "auth_photos/" + imgName + ".jpg", path);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                String url_log = "https://image.zhenfujin.net/" + "auth_photos/" + imgName + ".jpg";
                runOnUiThread(() -> authInfo(url_log));
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("onFailure", serviceException.getErrorCode());
                    Log.e("onFailure", serviceException.getRequestId());
                    Log.e("onFailure", serviceException.getHostId());
                    Log.e("onFailure", serviceException.getRawMessage());
                    UIUtils.showToastSafe("图片上传失败，请重新上传");
                }
            }
        });
    }

    private void authInfo(String url_log) {
        List<String> path = new ArrayList<>();
        path.add(url_log);
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> params2 = new HashMap<>();
        params2.put("auth_name", etName.getText().toString().trim());
        params2.put("auth_code", company_name_code.getText().toString().trim());
        params2.put("auth_type", 2 + "");
        params2.put("auth_code_type", 4 + "");
        params2.put("flie_list", path);
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.AUTHINFO, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean resultBean) {
                UIUtils.showToastSafe("提交成功");
                finish();
            }
        });
    }


    private void initOss() {
        String endpoint = "http://oss-cn-zhangjiakou.aliyuncs.com";
        // 在移动端建议使用STS方式初始化OSSClient。
        // 更多信息可查看sample 中 sts 使用方式(https://github.com/aliyun/aliyun-oss-android-sdk/tree/master/app/src/main/java/com/alibaba/sdk/android/oss/app)
        //   OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.ACCESS_ID, Constants.ACCESS_KEY);

        //该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    }

    private String revitionImageSize(String path) {
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; //只读取图片，不加载到内存中
            BitmapFactory.decodeStream(in, null, options);
            in.close();

            options.inJustDecodeBounds = false;
            int w = options.outWidth;
            int h = options.outHeight;
            float hh = 800f;//
            float ww = 480f;//
            int be = 1;
            if (w > h && w > ww) {
                be = (int) (options.outWidth / ww);
            } else if (w < h && h > hh) {
                be = (int) (options.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            options.inSampleSize = be;//设置采样率

            options.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设
            options.inPurgeable = true;// 同时设置才会有效
            options.inInputShareable = true;//。当系统内存不够时候图片自动被回收
            String newPath = Constants.APP_FOLD + path.substring(path.lastIndexOf("/"));
            saveBitmapToFile(bitmap, newPath);
            // bitmap = BitmapFactory.decodeFile(path, options);
            return newPath;
        } catch (Exception e) {
            e.printStackTrace();
            return path;
        }
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param _file
     * @throws IOException
     */
    public void saveBitmapToFile(Bitmap bitmap, String _file)
            throws IOException {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void showDialog() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait, null);
        //初始控件
        dialogView.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        dialogView.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        dialogView.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(dialogView);
        //获取当前Activity所在窗体
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }

        dialog.show();//显示对话框
        window.setGravity(Gravity.BOTTOM);//设置dialog从窗体底部弹出
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        lp.y = 20;
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) { //拍照
            mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));

        } else if (requestCode == RC_PHOTO_PREVIEW) {   //相册
            mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
        }


        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(imageUri, this);
                    if (bitmap != null) {
                        isShowImg = true;
                        company_imageview.setImageBitmap(bitmap);
                    }
                   // cropImageUri = Uri.fromFile(fileCropUri);
                   // PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                   // cropImageUri = Uri.fromFile(fileCropUri);
                     imageUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        imageUri = FileProvider.getUriForFile(this, "com.dai.zhenfujin.FileProvider", new File(imageUri.getPath()));
                    }
                  //  PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    Bitmap bitmap2 = PhotoUtil.getBitmapFromUri(imageUri, this);
                    if (bitmap2 != null) {
                        isShowImg = true;
                        company_imageview.setImageBitmap(bitmap2);
                    }
                    break;
                case CODE_RESULT_REQUEST:
                  //  Bitmap bitmap = PhotoUtil.getBitmapFromUri(imageUri, this);
                   /* if (bitmap != null) {
                        isShowImg = true;
                        company_imageview.setImageBitmap(bitmap);
                    }*/
                    break;
                default:
            }
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    private void choicePhotoWrapper() {
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "zhen");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(1) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }
}
